'use strict';
const axios = require('axios')
const semver = require('semver')
const urlJoin = require('url-join')

function getNpmInfo(npmName, registry) {
    if (!npmName) {
        return null
    }
    
    const realRegistry = registry || getDefaultRegistry()
    const npmInfoUrl = urlJoin(realRegistry, npmName)

    return axios({
        url: npmInfoUrl,
        method: 'get'
    }).then(response => {
        if (response.status === 200) {
            return response.data
        }
        return null
    }).catch(err => {
        return Promise.reject(err)
    })
}


async function getNpmVersions(npmName, registry) {
    const info = await getNpmInfo(npmName, registry)
    if (info && info.versions) {
        return Object.keys(info.versions)
    }
    return []
}


function getNpmSemverVersions(baseVersion, versions) {
    return versions.filter(version => semver.satisfies(version, `^${baseVersion}`))
        .sort((a, b) => semver.gt(a, b))
}


async function getNpmSemverVersion(baseVersion, npmName, registry) {
    const versions = await getNpmVersions(npmName, registry)
    const newVersions = getNpmSemverVersions(baseVersion, versions)
    if (newVersions && newVersions.length > 0) {
        return newVersions[0]
    }
}


function getDefaultRegistry(isOriginal = false) {
    return isOriginal ? 'https://registry.npmjs.org' : 'https://registry.npmmirror.com'
}

async function getNpmLatestVersion(npmName, registry) {
    let versions = await getNpmVersions(npmName, registry)
    if (versions) {
        // sort 必须是返回 1， -1
        versions = versions.sort((a, b) => semver.gt(a, b) ? -1 : 1)
        return versions[0]
    }
    return null
}

module.exports = {
    getNpmInfo,
    getNpmVersions,
    getNpmSemverVersion,
    getDefaultRegistry,
    getNpmLatestVersion
};
